//
//  MAMineViewController.m
//  MateAdv
//
//  Created by 茶 on 2023/9/15.
//

#import "MAMineViewController.h"
#import "MAMineView.h"
#import "MAMineTableViewCell.h"
#import <UMShare/UMShare.h>
#import <UShareUI/UShareUI.h>

@interface MAMineViewController ()

@property (nonatomic, strong) MAMineView *mineView;
@property (nonatomic, strong) NSArray *imgs;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) MAUserModel *model;

@end

@implementation MAMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self initInterface];
}

- (void)initInterface {
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName : MAFontScaleSemibold(18),
                                                                    NSForegroundColorAttributeName : UIColor.whiteColor};
    
    UIImage *image = [[UIImage imageNamed:@"nav_back_btn"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:nil action:nil];
    
    [self.tableView registerClass:MAMineTableViewCell.class forCellReuseIdentifier:kMineCellIdentifier];
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    CGFloat height = UIDevice.statusHeight;
    if (height <= 20) {
        height += 2;
    }
    self.tableView.contentInset = UIEdgeInsetsMake(-height, 0, 0, 0);
    self.tableView.alwaysBounceVertical = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.rowHeight = MARatioWidth(50);
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    MAWeakify(self);
    [ReqManager fetchUserInfoWithSuccessed:^(id  _Nonnull object) {
        if ([object containKey:@"user_info"]) {
            MAStrongify(self);
            [kUserDefaults setObject:object[@"user_info"] forKey:kUserInfo];
            if (self->_mineView) {
                self->_mineView.model = self.model;
            }
        }
    } failed:nil];
}

- (void)shareEvent {
    
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType,NSDictionary*userInfo){
        UIImage *appIcon = [UIImage imageNamed:@"app_logo"];
        
        //创建分享消息对象
        UMSocialMessageObject*messageObject =[UMSocialMessageObject messageObject];
        //创建网页内容对象
        UMShareWebpageObject*shareObject =[UMShareWebpageObject shareObjectWithTitle:@"情侣大冒险" descr:@"为情侣量身打造的情趣小工具！" thumImage:appIcon];
        //设置网页地址
        shareObject.webpageUrl = @"http://changxiu-oss.xtboo.com/zxh/web/policy/share_phone.html";
        NSDictionary *dic = MAUserObj(kAppInfo);
        if (dic && [dic containKey:@"common"]) {
            NSDictionary *common = [dic objectForKey:@"common"];
            if (common && [common containKey:@"url_share"]) {
                NSString *urlStr = [common objectForKey:@"url_share"];
                shareObject.webpageUrl = urlStr;
            }
        }
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data,NSError*error){
            if(error){
            NSLog(@"************Share fail with error %@*********",error);
            }else{
            NSLog(@"response data is %@",data);
            }
        }];
    }];
}

- (void)consumerEvent {
    MAWeakify(self);
    [LEEAlert alert].config
    .LeeTitle(@"客服")         // 添加一个标题 (默认样式)
    .LeeContent(WX_Customer_WX)        // 添加一个标题 (默认样式)
    .LeeAction(@"取消", ^{        //添加一个默认类型的Action (默认样式 字体颜色为蓝色)
    })
    .LeeCancelAction(@"联系客服", ^{    // 添加一个取消类型的Action (默认样式 alert中为粗体 actionsheet中为最下方独立)
        MAStrongify(self);
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = WX_Customer_WX;
        NSURL * url = [NSURL URLWithString:@"weixin://"];
        BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:url];
        //先判断是否能打开该url
        if (canOpen)
        {   //打开微信
            [self.view makeToast:@"已复制微信号，请到微信中添加"];
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        }else {
            [self.view makeToast:@"您的设备未安装微信APP"];
        }
    })
    .LeeShow();
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titles.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return self.mineView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MAMineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kMineCellIdentifier forIndexPath:indexPath];
    if (!cell) {
        cell = [[MAMineTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kMineCellIdentifier];
    }
    cell.title = self.titles[indexPath.row];
    cell.imgName = self.imgs[indexPath.row];
    // Configure the cell...
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return UIDevice.statusHeight + UIDevice.navHeight + MARatioWidth(250);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        [self shareEvent];
    } else if (indexPath.row == 1) {
        [self consumerEvent];
    } else if (indexPath.row == 2) {
        [UIApplication.sharedApplication openURL:[NSURL URLWithString:kPrivacyURL] options:@{} completionHandler:nil];
    } else if (indexPath.row == 3) {
        [UIApplication.sharedApplication openURL:[NSURL URLWithString:kUserAgreementURL] options:@{} completionHandler:nil];
    } else if (indexPath.row == 4) {
        NSString * nsStringToOpen = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?action=write-review", @"6466156393"];//替换为对应的APPID
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:nsStringToOpen] options:@{} completionHandler:nil];
    } else if (indexPath.row == 5) {
        [self.navigationController pushViewController:[NSClassFromString(@"MASettingViewController") new] animated:YES];
    }
}

- (NSArray *)imgs {
    if (_imgs) return _imgs;
    _imgs = @[@"Mine_Share", @"Mine_Connect", @"Mine_Privacy", @"Mine_User", @"Mine_Good", @"Mine_Setting"];
    return _imgs;
}

- (NSArray *)titles {
    if (_titles) return _titles;
    _titles = @[@"分享好友", @"联系我们", @"隐私政策", @"用户协议", @"给个好评", @"设置"];
    return _titles;
}

- (MAMineView *)mineView {
    if (_mineView) return _mineView;
    MAWeakify(self);
    _mineView = [MAMineView new];
    _mineView.model = self.model;
    _mineView.copyBlock = ^(NSString * _Nonnull userID) {
        MAStrongify(self);
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = userID;
        [self.view makeToast:@"已复制"];
    };
    _mineView.payBlock = ^{
        MAStrongify(self);
        [self.navigationController pushViewController:[NSClassFromString(@"MAVipViewController") new] animated:YES];
    };
    return _mineView;
}

- (MAUserModel *)model {
    _model = [MAUserModel new];
    [_model yy_modelSetWithJSON:MAUserObj(kUserInfo)];
    return _model;
}

@end
